/*
 * main.cpp
 *
 *  Created on: Feb 10, 2011
 *      Author: dblyth
 */

#include <iostream>
#include <stdlib.h>
using namespace std;

#include <TSystem.h>

#include "RunData.h"

char* getArg(char arg, int argc, char** argv);
void printHelp();

int main(int argc, char** argv) {
	gSystem->Load("libTree");

	char* fileName = getArg('f', argc, argv);
	if (fileName == NULL)
		return 0;

	char* runName = getArg('r', argc, argv);
	if (runName == NULL)
		return 0;

	TFile* file = new TFile(fileName);
	RunData* run = new RunData(file, runName);

	char* numBinsString = getArg('b', argc, argv);
	if (numBinsString == NULL)
		return 0;
	unsigned int numBins = atoi(numBinsString);
	int spectrum[numBins];
	int counts = 0;
	for (int i = 0; i < run->getNumChannels(); i++) {
		for (int j = 0; j < numBins; j++)
			spectrum[j] = 0;
	}

	char* minValueString = getArg('m', argc, argv);
	if (minValueString == NULL)
		return 0;
	int minValue = atoi(minValueString);

	char* maxValueString = getArg('M', argc, argv);
	if (maxValueString == NULL)
		return 0;
	int maxValue = atoi(maxValueString);

	double binWidth = ((double) maxValue - minValue) / numBins;

	double numPedSamples = 40;

	for (int l = 0; l < run->getEntryCount(); l++) {
		unsigned short** data = run->getEntry(l);

		double sum = 0;
		for (int i = 0; i < run->getNumChannels(); i++) {
			double ped = 0;
			int total = 0;
			for (int j = 0; j < run->getSamplesPerChannel(); j++) {
				total += data[i][j];
				if (j < numPedSamples)
					ped += data[i][j];
			}
			ped *= ((double) run->getSamplesPerChannel()) / numPedSamples;

			double tempSum = ped - total;

			sum += tempSum;

			delete[] data[i];
		}

		counts++;
		if (sum >= minValue && sum <= maxValue) {
			unsigned int bin = (int) (sum - minValue) / (double) binWidth;
			if (bin < numBins) {
				spectrum[bin]++;
			}
		}

		delete[] data;
	}

	delete run;

	file->Close();

	for (int i = 0; i < numBins; i++) {
		cout << (i + .5) * binWidth + minValue << "\t" << spectrum[i] << endl;
	}

	return 0;
}

char* getArg(char arg, int argc, char** argv) {
	for (int i = 1; i < argc - 1; i++) {
		if (argv[i][0] == '-' && argv[i][1] == arg) // && argv[i + 1][0] != '-')
			return argv[i + 1];
	}

	cout << "Bad syntax\n\n";
	printHelp();
	return NULL;
}

void printHelp() {
	cout << "Usage: acess -f FILENAME -r RUNNAME -b NUMBINS -m MIN -M MAX"
			<< endl;
}
